/* eslint-disable antfu/no-top-level-await */

import fs from 'node:fs'
import fsp from 'node:fs/promises'
import { createRequire } from 'node:module'
import os from 'node:os'
import path from 'node:path'
import process from 'node:process'

import { cancel, intro, isCancel, log, outro, select } from '@clack/prompts'
import dotenv from 'dotenv'
import { isEmpty } from 'lodash-es'
import { $, usePowerShell } from 'zx'

// console.log(process.env)

if (os.platform() === 'win32') {
  usePowerShell()
}

const CWD = process.cwd()
const PACKAGE = createRequire(import.meta.url)(path.join(CWD, 'package.json'))

const platformOptions = [
  { label: 'h5', value: { name: 'h5', args: [] }, hint: 'H5' },
  { label: 'mp-alipay', value: { name: 'mp-alipay', args: ['-p', 'mp-alipay'] }, hint: '支付宝小程序' },
  { label: 'mp-weixin', value: { name: 'mp-weixin', args: ['-p', 'mp-weixin'] }, hint: '微信小程序' },
  { label: 'mp-kuaishou', value: { name: 'mp-kuaishou', args: ['-p', 'mp-kuaishou'] }, hint: '快手小程序' },
  { label: 'mp-toutiao', value: { name: 'mp-toutiao', args: ['-p', 'mp-toutiao'] }, hint: '抖音小程序' },
  { label: 'app', value: { name: 'app', args: ['-p', 'app'] }, hint: 'App' },
  { label: 'app-android', value: { name: 'app-android', args: ['-p', 'app-android'] }, hint: '安卓 App' },
  { label: 'app-ios', value: { name: 'app-ios', args: ['-p', 'app-ios'] }, hint: ' iOS App' },
  { label: 'app-harmony', value: { name: 'app-harmony', args: ['-p', 'app-harmony'] }, hint: '鸿蒙 App' },
  { label: 'custom', value: { name: 'custom', args: ['-p'] }, hint: '自定义' },
  { label: 'h5:ssr', value: { name: 'h5-ssr', args: ['--ssr'] }, hint: 'H5 SSR' },
  { label: 'mp-baidu', value: { name: 'mp-baidu', args: ['-p', 'mp-baidu'] }, hint: '百度小程序' },
  { label: 'mp-jd', value: { name: 'mp-jd', args: ['-p', 'mp-jd'] }, hint: '京东小程序' },
  { label: 'mp-lark', value: { name: 'mp-lark', args: ['-p', 'mp-lark'] }, hint: '飞书小程序' },
  { label: 'mp-qq', value: { name: 'mp-qq', args: ['-p', 'mp-qq'] }, hint: 'QQ 小程序' },
  { label: 'mp-xhs', value: { name: 'mp-xhs', args: ['-p', 'mp-xhs'] }, hint: '小红书 小程序' },
  { label: 'quickapp-webview', value: { name: 'quickapp-webview', args: ['-p', 'quickapp-webview'] }, hint: '快应用' },
  { label: 'quickapp-webview-huawei', value: { name: 'quickapp-webview-huawei', args: ['-p', 'quickapp-webview-huawei'] }, hint: '快应用' },
  { label: 'quickapp-webview-union', value: { name: 'quickapp-webview-union', args: ['-p', 'quickapp-webview-union'] }, hint: '快应用' },
]

function cancelGuard(x) {
  if (isCancel(x)) {
    cancel('操作取消')
    process.exit(0)
  }
}

try {
  intro(`MDM 租赁小程序 v${PACKAGE.version}`)

  /* 用户交互 */

  // 运行模式
  const runMode = await select({
    message: '选择运行模式',
    options: [
      { label: '开发', value: 'dev' },
      { label: '打包', value: 'build' },
    ],
  })
  cancelGuard(runMode)

  // 机构项目（从 env 目录读取）
  const viteModeOptions = await (async () => {
    const envFiles = (await fsp.readdir('env')).filter(x => x.startsWith('.env.'))
    const options = []
    for (const fileName of envFiles) {
      const fileContent = await fsp.readFile(path.join(CWD, 'env', fileName), 'utf8')
      const envFileContent = dotenv.parse(fileContent)

      options.push({
        label: envFileContent.X_NAME,
        value: {
          name: /^\.env\.(.+)$/.exec(fileName)[1],
          platforms: envFileContent.X_PLATFORMS.split(',').filter(x => platformOptions.map(y => y.label).includes(x)),
          theme: envFileContent.X_THEME,
        },
        hint: fileName,
      })
    }
    return options
  })()
  const viteMode = await select({
    message: '选择机构项目',
    options: viteModeOptions,
  })
  cancelGuard(viteMode)

  // 编译平台
  const platform = await select({
    message: '选择编译平台',
    options: platformOptions.filter(x => viteMode.platforms.includes(x.value.name)),
  })
  cancelGuard(platform)

  /* 不同主题文件合并 */

  // 删除静态资源目录
  await fsp.rm(path.join(CWD, 'src', 'static'), { recursive: true, force: true })

  const mergePaths = await (async () => {
    const publicFiles = (await fsp.readdir(path.join(CWD, 'theme_static', 'public'), { recursive: true }))
      .map(x => path.join('public', x))
    const themeFiles = (await fsp.readdir(path.join(CWD, 'theme_static', viteMode.theme), { recursive: true }))
      .map(x => path.join(viteMode.theme, x))

    const paths = [...publicFiles, ...themeFiles]
      .filter(x => !x.endsWith('.DS_Store'))
      .filter(x => fs.statSync(path.join(CWD, 'theme_static', x)).isFile())

    return paths
  })()

  // 提前创建目录
  const newDirs = (() => {
    const list = []
    for (const filePath of mergePaths) {
      const dirName = path.dirname(filePath)
      const usefulDirNames = dirName.split(path.sep).slice(1)
      if (!isEmpty(usefulDirNames)) {
        list.push(JSON.stringify(usefulDirNames))
      }
    }
    return [...new Set(list)].map(x => JSON.parse(x))
  })()

  for (const dir of newDirs) {
    await fsp.mkdir(path.join(CWD, 'src', 'static', ...dir), { recursive: true })
  }

  // 复制文件
  for (const filePath of mergePaths) {
    await fsp.copyFile(
      path.join(CWD, 'theme_static', filePath),
      path.join(CWD, 'src', 'static', ...filePath.split(path.sep).slice(1)),
    )
  }
  // process.exit(0)

  // TODO 根据 pages.json 生成 src/types/route-path.ts 定义

  /* 项目执行 */

  log.step('执行中')

  const $$ = $({
    preferLocal: true,
    verbose: true,
    env: {
      ...process.env,
      FORCE_COLOR: 3,
      PRODUCT_ENV: viteMode.name,
      PRODUCT_THEME: viteMode.theme,
    },
  })
  if (runMode === 'dev') {
    await $$`uni ${runMode} --mode ${viteMode.name} ${platform.args}`
  }
  else if (runMode === 'build') {
    await $$`uni ${runMode} --mode ${viteMode.name} --outDir dist/${viteMode.name}_${platform.name}_v${PACKAGE.version} ${platform.args}`
  }

  outro('完成')
}
catch (error) {
  console.error(error)
}
